#include "date.h"
#include <stdint.h>

extern uint8_t year, month, date, hour, minute, second, day;

uint8_t is_leapyear() {
    // 对于20xx年，被4整除就是闰年
    if (year & 0x03) {
        return 0;
    } else {
        return 1;
    }
}

uint8_t next_date() {
    switch (month) {
        case 2:
            if (is_leapyear()) {
                if (date >= 29) {
                    return 0;
                } else {
                    return date + 1;
                }
            } else {
                if (date >= 28) {
                    return 0;
                } else {
                    return date + 1;
                }
            }
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            if (date >= 30) {
                return 1;
            } else {
                return date + 1;
            }
            break;
        default:
            if (date >= 31) {
                return 1;
            } else {
                return date + 1;
            }
            break;
    }
}

uint8_t prev_date() {
    switch (month) {
        case 2:
            if (is_leapyear()) {
                if (date <= 1) {
                    return 29;
                } else {
                    return date - 1;
                }
            } else {
                if (date <= 1) {
                    return 28;
                } else {
                    return date - 1;
                }
            }
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            if (date <= 1) {
                return 30;
            } else {
                return date - 1;
            }
            break;
        default:
            if (date <= 1) {
                return 31;
            } else {
                return date - 1;
            }
            break;
    }
}

uint8_t get_day_of_week_from_date() {
    // (date + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + year/400) % 7
    if (is_leapyear() && month==2) {
        return (date + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + 3) % 7;
    } else if (month==2){
        return (date + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + 4) % 7;
    } else {
        return (date + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + 1) % 7;
    }
}
